<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Gmap
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Gmap_IndexController extends Core_Controller_Action_Standard
{
  protected $_navigation;

  public function init()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('gmap', null, 'view')->isValid() ) return;
    
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      if( 0 !== ($gmap_id = (int) $this->_getParam('gmap_id')) &&
          null !== ($gmap = Engine_Api::_()->getItem('gmap', $gmap_id)) )
      {
        Engine_Api::_()->core()->setSubject($gmap);
      }
    }
    
    $this->_helper->requireUser->addActionRequires(array(
      'create',
      'delete',
      'edit',
      'manage',
      'success',
      'coordinate',
    ));

    $this->_helper->requireSubject->setActionRequireTypes(array(
      'delete' => 'gmap',
      'edit' => 'gmap',
      'preview' => 'gmap',
      'success' => 'gmap',
      'publish' => 'gmap',
      'view' => 'gmap',
      'edit-coordinate' => 'gmap',
    ));
  }
  
  
  public function indexAction()
  {
  	
    $this->_helper->content->setNoRender()->setEnabled();
  }
  
  
  public function membersAction()
  {
    $require_check = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.general.browse', 1);
    if(!$require_check){
      if( !$this->_helper->requireUser()->isValid() ) return;
    }
    
    $this->view->navigation = $this->getNavigation();
    
    if( !$this->_executeSearchMembers() ) {
      throw new Exception('error');
    }
    
    if( $this->_getParam('ajax') ) {
      $this->renderScript('_browseUsers.tpl');
    }
  }
  

  // modified from User/IndexController.php
  protected function _executeSearchMembers()
  {
    // Check form
    $form = new Gmap_Form_Members(array(
      'type' => 'user'
    ));

    if( !$form->isValid($this->_getAllParams()) ) {
      $this->view->error = true;
      return false;
    }

    $this->view->form = $form;

    // Get search params
    $page = (int)  $this->_getParam('page', 1);
    $ajax = (bool) $this->_getParam('ajax', false);
    $options = $form->getValues();

    $params = array(
	    'home' => 1,
	    'mappable' => 1,
    );
    
    if (isset($options['gmaplocation']) && strlen($options['gmaplocation'])) {
	    $google_map = new Radcodes_Lib_Google_Map();
	    $geocoded_address = $google_map->geocode($options['gmaplocation']);
	    
	    // location found
	    if ($geocoded_address) {
	      $params['location'] = $options['gmaplocation'];
	      $params['distance'] = $options['gmapdistance'];
	    }
	    else {
        $this->view->error = true;
        return false;
	    }

    }
    
    $select = Engine_Api::_()->gmap()->getGmapsSelect($params);
    $gmaps = $select->query()->fetchAll();
    $user_ids = array();
    foreach ($gmaps as $gmap) {
      $user_ids[$gmap['owner_id']] = $gmap['owner_id'];
    }
    
    // Get table info
    $table = Engine_Api::_()->getItemTable('user');
    $userTableName = $table->info('name');

    $searchTable = Engine_Api::_()->fields()->getTable('user', 'search');
    $searchTableName = $searchTable->info('name');

    //extract($options); // displayname
    $profile_type = @$options['profile_type'];
    $displayname = @$options['displayname'];
    extract($options['extra']); // is_online, has_photo, submit

    // Contruct query
    $select = $table->select()
      //->setIntegrityCheck(false)
      ->from($userTableName)
      ->joinLeft($searchTableName, "`{$searchTableName}`.`item_id` = `{$userTableName}`.`user_id`", null)
      //->group("{$userTableName}.user_id")
      ->where("{$userTableName}.search = ?", 1)
      ->where("{$userTableName}.enabled = ?", 1)
      ->where("{$userTableName}.verified = ?", 1)
      ->order("{$userTableName}.displayname ASC");
      
    if (is_array($user_ids)) {
      $select->where("{$userTableName}.user_id IN (?)", new Zend_Db_Expr("'" . join("', '", $user_ids) . "'"));
    }
    
    // Build the photo and is online part of query
    if( !empty($has_photo) ) {
      $select->where($userTableName.'.photo_id != ?', "0");
    }

    if( !empty($is_online) ) {
      $select
        ->joinRight("engine4_user_online", "engine4_user_online.user_id = `{$userTableName}`.user_id", null)
        ->group("engine4_user_online.user_id")
        ->where($userTableName.'.user_id != ?', "0");
    }

    // Add displayname
    if( !empty($displayname) ) {
      $select->where("(`{$userTableName}`.`username` LIKE ? || `{$userTableName}`.`displayname` LIKE ?)", "%{$displayname}%");
    }

    // Build search part of query
    $searchParts = Engine_Api::_()->fields()->getSearchQuery('user', $options);
    foreach( $searchParts as $k => $v ) {
      $select->where("`{$searchTableName}`.{$k}", $v);
    }

    // Build paginator
    $limit = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.page', 20);
    $paginator = Zend_Paginator::factory($select);
    $paginator->setItemCountPerPage($limit);
    $paginator->setCurrentPageNumber($page);
    
    $this->view->page = $page;
    $this->view->ajax = $ajax;
    $this->view->users = $paginator;
    $this->view->totalUsers = $paginator->getTotalItemCount();
    $this->view->userCount = $paginator->getCurrentItemCount();
    $this->view->topLevelId = $form->getTopLevelId();
    $this->view->topLevelValue = $form->getTopLevelValue();
    $this->view->formValues = array_filter($options);

    $member_ids = array();
    foreach ($paginator as $user) {
      $member_ids[] = $user->getIdentity();
    }
    
    $this->view->gmapPaginator = Engine_Api::_()->gmap()->getMappableGmapsPaginator(array(
      'users' => $member_ids,
	    'home' => 1,
	    'mappable' => 1,    
      'order' => 'creation_date',
      'order_direction' => 'DESC',
      'limit' => count($member_ids)
    ));
    
    $gmaps = array();
    foreach ($this->view->gmapPaginator as $gmap) {
      $gmaps[$gmap->owner_id] = $gmap;
    }
    $this->view->gmaps = $gmaps;
    
    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_members');
    
    return true;
  }  
  
  
  // NONE USER SPECIFIC METHODS
  public function browseAction()
  {
  	
  	
    $viewer = Engine_Api::_()->user()->getViewer();
       
    $this->view->navigation = $this->getNavigation();
    $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->checkRequire();

    $this->view->form = $form = new Gmap_Form_Search();
               
    if( !$viewer->getIdentity() )
    {
      $form->removeElement('show');
    }

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }
    
    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    
    if( !empty($values['category']) )
    {
      $this->view->categoryObject = Engine_Api::_()->gmap()->getCategory($values['category']);
    }    

    
    $this->view->formValues = $values;
    
    if( $viewer->getIdentity() && @$values['show'] == 1 )
    {   	
      $values['users'] = array();
      foreach( $viewer->membership()->getMembersInfo(true) as $memberinfo )
      {
        $values['users'][] = $memberinfo->user_id;
      }
    }

    // check to see if request is for specific user's gmaps
    $user_id = $this->_getParam('user');
    if ($user_id) $values['user_id'] = $user_id;
   
    $this->view->assign($values);
    
    // items needed to show what is being filtered in browse page
    if (!empty($values['tag'])) 
    {
    	$this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }


    
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.page', 20);
    $values['pre_order'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.sorting', 0);
    $values['distance_unit'] = Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.distanceunit', Radcodes_Lib_Helper_Unit::UNIT_MILE);
    
    //Engine_Api::_()->getApi('debug','radcodes')->log($values,'values');
    
    $this->view->paginator = $paginator = Engine_Api::_()->gmap()->getMappableGmapsPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));
    
    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_browse');

  }


  
  
  public function manageAction()
  {
    if( !$this->_helper->requireUser()->isValid() ) return;
 
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->checkRequire();
    $this->view->allowed_upload = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'photo');

    $this->view->navigation = $this->getNavigation();
    $this->view->form = $form = new Gmap_Form_Search();
    $form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array(),'gmap_manage',true));
    
    $form->removeElement('show');

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }


    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
    
    $values['user_id'] = $viewer->getIdentity();
    $this->view->assign($values);
    
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.page', 20);

    // Get paginator
    $this->view->paginator = $paginator = Engine_Api::_()->gmap()->getGmapsPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    

    // maximum allowed gmaps
    $this->view->quota = $quota = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'max');
    $this->view->current_count = $paginator->getTotalItemCount();
    
    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_list');
    
    $this->view->has_gmap_home = Engine_Api::_()->gmap()->hasGmapHome($viewer->getIdentity());
  }


  
  
  public function viewAction()
  {
  	
  	
  	
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->gmap = $gmap = Engine_Api::_()->core()->getSubject('gmap');
 
    $this->view->owner = $owner = Engine_Api::_()->user()->getUser($gmap->owner_id);
    
    $this->view->canEdit = $this->_helper->requireAuth()->setAuthParams($gmap, null, 'edit')->checkRequire();
    $this->view->canUpload = $this->_helper->requireAuth()->setAuthParams($gmap, null, 'photo')->checkRequire();
    $this->view->canDelete = $this->_helper->requireAuth()->setAuthParams($gmap, null, 'delete')->checkRequire();
    $this->view->canPublish = $gmap->isOwner($viewer) && !$gmap->isMappable();
        
    $gmap->view_count++;
    $gmap->save();
    
    $this->view->gmap = $gmap;
    if ($gmap->photo_id)
    {
      $this->view->main_photo = $gmap->getPhoto($gmap->photo_id);
    }
    // get tags
    $this->view->gmapTags = $gmap->tags()->getTagMaps();
    $this->view->userTags = $gmap->tags()->getTagsByTagger($gmap->getOwner());
    

    $view = $this->view;
    $view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
    $this->view->fieldStructure = $fieldStructure = Engine_Api::_()->fields()->getFieldsStructurePartial($gmap);
    
    // album material
    $this->view->album = $album = $gmap->getSingletonAlbum();
    $this->view->paginator = $paginator = $album->getCollectiblesPaginator();
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));
    $paginator->setItemCountPerPage(Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.gallery', 3));
    
    if($gmap->category_id !=0) $this->view->category = Engine_Api::_()->gmap()->getCategory($gmap->category_id);
    $this->view->userCategories = Engine_Api::_()->gmap()->getUserCategories($this->view->gmap->owner_id);
        
    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_view');

    $other_gmaps_params = array(
      'exclude_gmap_ids' => array($gmap->getIdentity()),
      'user_id' => $gmap->owner_id,
      'limit' => 5
    );
    $this->view->paginatorGmaps = $paginator = Engine_Api::_()->gmap()->getMappableGmapsPaginator($other_gmaps_params);
    /*
    if ($this->_getParam('format') == 'smoothbox')
    {
    	$this->renderScript('preview.tpl');
    }
    */
  }

    
  public function previewAction()
  {
  	$this->viewAction();
  }
  
  public function createAction()
  {
    //if( !$this->_helper->requireUser()->isValid() ) return;
    if( !$this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->isValid()) return;
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->navigation = $this->getNavigation();
    $this->view->form = $form = new Gmap_Form_Create();
    // set up data needed to check quota
    $values['user_id'] = $viewer->getIdentity();
    $paginator = $this->_helper->api()->getApi('core', 'gmap')->getGmapsPaginator($values);

    $this->view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
    
    $this->view->quota = $quota = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'max');
    $this->view->current_count = $paginator->getTotalItemCount();

    // If not post or form not valid, return
    if( $this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost()) )
    {
      $table = Engine_Api::_()->getItemTable('gmap');
      $db = $table->getAdapter();
      $db->beginTransaction();

      try
      {
      	$featured = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'featured') ? 1 : 0;
        $sponsored = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'sponsored') ? 1 : 0;
      	
        // Create gmap
        $values = array_merge($form->getValues(), array(
          'owner_type' => $viewer->getType(),
          'owner_id' => $viewer->getIdentity(),
          'featured' => $featured,
          'sponsored' => $sponsored,
        ));

        if ($values['home'])
        {
        	Engine_Api::_()->gmap()->clearGmapHome($viewer->getIdentity());
        }
        
        $gmap = $table->createRow();
        $gmap->setFromArray($values);
        $gmap->populateGeocodedFields();
        $gmap->save();

        // Set photo
        if( !empty($values['photo']) ) {
          $gmap->setPhoto($form->photo);
        }

        // Add tags
        $tags = preg_split('/[,]+/', $values['tags']);
        $tags = array_filter(array_map("trim", $tags));
        $gmap->tags()->addTagMaps($viewer, $tags);


        
        $customfieldform = $form->getSubForm('customField');
        $customfieldform->setItem($gmap);
        $customfieldform->saveValues();

        // CREATE AUTH STUFF HERE
        $auth = Engine_Api::_()->authorization()->context;  
        $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
  
        $auth_keys = array(
         'view' => 'everyone',
         'comment' => 'registered',
        );
        
        foreach ($auth_keys as $auth_key => $auth_default)
        {
          $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
          $authMax = array_search($auth_value, $roles);
          
          foreach( $roles as $i => $role )
          {
            $auth->setAllowed($gmap, $role, $auth_key, ($i <= $authMax));
          }
        }

        // Add activity only if gmap is mappable
        if ($gmap->isMappable()) {
          $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $gmap, 'gmap_new');
            if($action!=null){
              Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $gmap);
            }
        }
        
        
        // Commit
        $db->commit();
        
 
        // Redirect
        $allowed_upload = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'gmap', 'photo');

        if( $allowed_upload )
        {
          return $this->_helper->redirector->gotoRoute(array('gmap_id'=>$gmap->gmap_id), 'gmap_success', true);
        }
        else
        {
        	return $this->_helper->redirector->gotoRoute(array(), 'gmap_manage', true); 
        }

      }

      catch( Exception $e )
      {
        $db->rollBack();
        throw $e;
      }
    }
  }

  public function editAction()
  {

    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->gmap = $gmap = Engine_Api::_()->core()->getSubject('gmap');
    
    if( !$this->_helper->requireAuth()->setAuthParams($gmap, null, 'edit')->isValid())
    {
      return $this->_forward('requireauth', 'error', 'core');
    }

    // Get navigation
    $navigation = $this->getNavigation();
    $this->view->navigation = $navigation;

    $this->view->form = $form = new Gmap_Form_Edit(array(
      'item' => $gmap
    ));
    
    // only for create
    $form->removeElement('photo');

    $form->populate($gmap->toArray());

    $auth = Engine_Api::_()->authorization()->context;
    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
    $auth_keys = array(
     'view' => 'everyone',
     'comment' => 'registered',
    );
    
    $this->view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
    
    // Save gmap entry
    if( !$this->getRequest()->isPost() )
    {

      // prepare tags
      $gmapTags = $gmap->tags()->getTagMaps();
      
      $tagString = '';
      foreach( $gmapTags as $tagmap )
      {
        if( $tagString !== '' ) $tagString .= ', ';
        $tagString .= $tagmap->getTag()->getTitle();
      }

      $this->view->tagNamePrepared = $tagString;
      $form->tags->setValue($tagString);
      
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_field = 'auth_'.$auth_key;
        
        foreach( $roles as $i => $role )
        {
          if (isset($form->$auth_field->options[$role]) && 1 === $auth->isAllowed($gmap, $role, $auth_key))
          {
            $form->$auth_field->setValue($role);
          }
        }
      }
      
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Process

    // handle save for tags
    $values = $form->getValues();
    $tags = preg_split('/[,]+/', $values['tags']);
    $tags = array_filter(array_map("trim", $tags));

    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {
      if ($values['home'] && !$gmap->home)
      { 
        Engine_Api::_()->gmap()->clearGmapHome($viewer->getIdentity());
      }    	
    	
      $old_location = $gmap->location;
      
      $gmap->setFromArray($values);
      $gmap->modified_date = date('Y-m-d H:i:s');
      
      if ($gmap->location != $old_location)
      {
        $gmap->populateGeocodedFields();
      }
      
      $gmap->tags()->setTagMaps($viewer, $tags);
      $gmap->save();

      // Save custom fields
      $customfieldform = $form->getSubForm('customField');
      $customfieldform->setItem($gmap);
      $customfieldform->saveValues();

      // CREATE AUTH STUFF HERE
      $values = $form->getValues();
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
          
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($gmap, $role, $auth_key, ($i <= $authMax));
        }
      }
      
      // Add activity only if gmap is mappable
      $action = Engine_Api::_()->getDbtable('actions', 'activity')->getActionsByObject($gmap);
      if (count($action->toArray())<=0 && $gmap->isMappable()){
      	
      	if( $viewer->getIdentity() != $gmap->owner_id)
      	{
      		$owner = Engine_Api::_()->user()->getUser($gmap->owner_id);
      	}
      	else {
      		$owner = $viewer;
      	}
      	
        $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($owner, $gmap, 'gmap_new');
        if($action!=null){
          Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $gmap);
        }
      }
    
      // Rebuild privacy
      $actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
      foreach( $actionTable->getActionsByObject($gmap) as $action ) {
        $actionTable->resetActivityBindings($action);
      }
      $db->commit();


      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);
      $customfieldform->removeElement('submit');
      
      //$this->_helper->getHelper('FlashMessenger')->addMessage($savedChangesNotice);
      
      //return $this->_helper->redirector->gotoRoute(array(), 'gmap_manage', true);
      //return $this->_helper->redirector->gotoRoute(array('gmap_id'=>$gmap->gmap_id), 'gmap_edit', true);
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
  }
  


  public function deleteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->gmap = $gmap = Engine_Api::_()->core()->getSubject('gmap');
    
    //if( $viewer->getIdentity() != $gmap->owner_id && !$this->_helper->requireAuth()->setAuthParams($gmap, null, 'edit')->isValid())
    if( !$this->_helper->requireAuth()->setAuthParams($gmap, null, 'delete')->isValid()) return;

    // Get navigation
    $navigation = $this->getNavigation();
    $this->view->navigation = $navigation;
    
    if( $this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true )
    {
      $this->view->gmap->delete();
      return $this->_helper->redirector->gotoRoute(array(), 'gmap_manage', true);
    }
  }
  
  
  public function editCoordinateAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->gmap = $gmap = Engine_Api::_()->core()->getSubject('gmap');
    
    if( !$this->_helper->requireAuth()->setAuthParams($gmap, null, 'edit')->isValid())
    {
      return $this->_forward('requireauth', 'error', 'core');
    }

    // Get navigation
    $navigation = $this->getNavigation();
    $this->view->navigation = $navigation;

    $this->view->form = $form = new Gmap_Form_Coordinate(array(
      'item' => $gmap
    ));
    
    $form->populate($gmap->toArray());
    
   
    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_edit_coordinate');
    
    $this->view->dragend_event = $dragend_event = new Radcodes_Lib_Google_Map_Event('dragend','marker_locator_coordinate', false);
    $this->view->marker = $marker = new Radcodes_Lib_Google_Map_Marker($form->lat->getValue(), $form->lng->getValue(), array('draggable'=>'true','title'=>'Drag Me'), 'marker_locator');
    $marker->addEvent($dragend_event);
    
    $google_map->addMarker($marker);
    
    if( !$this->getRequest()->isPost() || !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Process

    // handle save for tags
    $values = $form->getValues();

    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {
      $gmap->setFromArray($values);

      $gmap->save();

      $db->commit();

      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);

      $marker->setCoord($gmap->getMapCoord());
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
  }
  
  public function successAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->gmap = $gmap = Engine_Api::_()->core()->getSubject('gmap');
    
    if( $viewer->getIdentity() != $gmap->owner_id )
    {
      return $this->_forward('requireauth', 'error', 'core');
    }    
    
    $this->view->navigation = $this->getNavigation();

    if( $this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true )
    {
    	return $this->_helper->redirector->gotoRoute(array('controller'=>'photo','action'=>'upload','subject'=>$gmap->getGuid()), 'gmap_extended', true);
    }
  }


  public function listAction()
  {
    
    
    $owner_id = $this->_getParam('user_id');
    
    $this->view->owner = $owner = Engine_Api::_()->user()->getUser($owner_id);
    
    if (!$owner->getIdentity())
    {
    	return $this->_forward('requiresubject', 'error', 'core');
    }
    
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->checkRequire() && $viewer->getIdentity() == $owner->getIdentity();

    $this->view->navigation = $this->getNavigation();

    $this->view->categories = $categories = Engine_Api::_()->gmap()->getCategories();

    $values = array();
    $values['user_id'] = $owner->getIdentity();
    $values['category'] = $this->_getParam('category');
    $values['tag'] = $this->_getParam('tag');
    
    $this->view->assign($values);
    
    $view = $this->view;
    $view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
       
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.page', 10);
    // Get paginator
    $this->view->paginator = $paginator = Engine_Api::_()->gmap()->getMappableGmapsPaginator($values, array());
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    

    $this->view->google_map = $google_map = Engine_Api::_()->getApi('map', 'radcodes')->getInstance('gmap_list');
    
    $this->view->userTags = Engine_Api::_()->getDbtable('tags', 'core')->getTagsByTagger('gmap', $owner);
    $this->view->userCategories = Engine_Api::_()->gmap()->getUserCategories($owner_id);

  }
  
  public function tagsAction()
  {
    
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->form = $form = new Gmap_Form_Search();
               
    if( !$viewer->getIdentity() )
    {
      $form->removeElement('show');
    }
    
    $this->view->navigation = $this->getNavigation();
    $this->view->can_create = $this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->checkRequire();
    
    $this->view->tags = $tags = Engine_Api::_()->gmap()->getPopularTags(array('limit' => 999, 'order' => 'text'));
  }
  
  
  public function getNavigation($active = false)
  {
    $this->_navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('gmap_main');
    
    /*
    if( is_null($this->_navigation) )
    {
      $navigation = $this->_navigation = new Zend_Navigation();

      $navigation->addPage(array(
        'label' => Zend_Registry::get('Zend_Translate')->_('Browse Gmaps'),
        'route' => 'gmap_browse',
        'module' => 'gmap',
        'controller' => 'index',
        'action' => 'browse'
      ));
      
      if( Engine_Api::_()->user()->getViewer()->getIdentity() )
      {
        $navigation->addPage(array(
          'label' => Zend_Registry::get('Zend_Translate')->_('My Gmaps'),
          'route' => 'gmap_manage',
          'module' => 'gmap',
          'controller' => 'index',
          'action' => 'manage',
          'active' => $active
        ));
        if( $this->_helper->requireAuth()->setAuthParams('gmap', null, 'create')->checkRequire()){
          $navigation->addPage(array(
            'label' => Zend_Registry::get('Zend_Translate')->_('Post New Gmap'),
            'route' => 'gmap_create',
            'module' => 'gmap',
            'controller' => 'index',
            'action' => 'create'
          ));
        }
      }
      
      $navigation->addPage(array(
        'label' => Zend_Registry::get('Zend_Translate')->_('Member Locations'),
        'route' => 'gmap_general',
        'module' => 'gmap',
        'controller' => 'index',
        'action' => 'members'
      ));
    }
    */
    return $this->_navigation;
  }

  
  public function handleArchiveList($results)
  {
    $archive_list = array();
    
    foreach ($results as $result)
    {
    	$gmap_date = strtotime($result['period']);
    	
      $date_info = Radcodes_Lib_Helper_Date::archive($gmap_date);
      $date_start = $date_info['date_start'];
      
      if( !isset($archive_list[$date_start]) )
      {
        $archive_list[$date_start] = $date_info;
        $archive_list[$date_start]['count'] = $result['total'];
      }
      else
      {
        $archive_list[$date_start]['count'] += $result['total'];
      }
    }

    return $archive_list;
  }
  
  

  protected function publicViewPermissionRequires()
  {
  	// NOTE: boolean return is not really needed - since it auto redirect to login/no permission screen
  	
    // require log in --- and -- not logged in => show log in screen
    if ( !Engine_Api::_()->getApi('settings', 'core')->getSetting('gmap.public', 1) && !$this->_helper->requireUser()->isValid() )
    { 
      return false;
    }
    
    // logged in && no view permission => show no permission
    if ( $this->_helper->requireUser()->checkRequire() && !$this->_helper->requireAuth()->setAuthParams('gmap', null, 'view')->isValid())
    {
      return false;
    }
    
    return true;
  }
  
}

